﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.Data;
using System.Xml;

using log4net;
using log4net.Config;

using SPW2HO.DataAccess;
using SPW2HO.CommonItems;

namespace SPW2HO.Classes
{
    public class Import
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Import));

        public static DirectoryInfo dirDownload = new DirectoryInfo(ConfigurationManager.AppSettings["DownloadFolder"].ToString());
        private static DirectoryInfo dirExtract = new DirectoryInfo(ConfigurationManager.AppSettings["ExtractFolder"].ToString());
        private static DirectoryInfo dirBackup = new DirectoryInfo(ConfigurationManager.AppSettings["BackupFolder"].ToString());
        private static DirectoryInfo dirBackupError = new DirectoryInfo(ConfigurationManager.AppSettings["BackupErrorFolder"].ToString());

        private static string AddImportTimeSuffix(string FileName)
        {
            string newName = FileName.Substring(0, FileName.LastIndexOf('.'));
            string ext = FileName.Substring(FileName.LastIndexOf('.'), FileName.Length - FileName.LastIndexOf('.'));
            newName += "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
            return newName;
        }

        #region 'Distributor Info'
        /// <summary>
        /// Import a file as distributor info
        /// </summary>
        /// <param name="f">FileInfo of the import file</param>
        /// <returns>'1' when import successful / '0' when import failed</returns>
        public static int ImportDistributorFile(FileInfo f)
        {
            int result = 1;
            FileInfo tmpFile = null;
            try
            {
                log.Info("Begin import file " + f.Name);

                Cryptography encode = new Cryptography();
                string pwd = encode.GenPWDByFilename(f.Name);
                Zip.UnzipFile(f.FullName, dirExtract.FullName, pwd);

                log.Info(" - " + f.Name + " decrypted successful");

                FileInfo[] XmlList = dirExtract.GetFiles("SPW2_DistributorInfo*");
                foreach (FileInfo xmlFile in XmlList)
                {
                    tmpFile = xmlFile;
                    DataTable dt = new DataTable();
                    dt.ReadXml(xmlFile.FullName);
                    foreach (DataRow dr in dt.Rows)
                    {
                        DistInfoBO obj = new DistInfoBO(dr[0].ToString(), 
                            dr[1].ToString(), 
                            dr[2].ToString(),
                            dr[3].ToString(), 
                            dr[4].ToString(), 
                            dr[5].ToString(), 
                            dr[6].ToString(), 
                            dr[7].ToString(), 
                            dr[8].ToString(), 
                            dr[9].ToString(), 
                            dr[10].ToString(), 
                            dr[11].ToString());
                        obj.ConvertToTCVN();
                        if (obj.Save() == -1)
                        {
                            result = 0;
                            break;
                        }
                    }
                    xmlFile.Delete();
                    log.Info(" - " + xmlFile.Name + " is imported successful");
                }
                log.Info(" - " + f.Name + " is imported successful");
                if (result == 1)
                {
                    f.MoveTo(Path.Combine(dirBackup.FullName, AddImportTimeSuffix(f.Name)));
                }
                else
                {
                    f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                }
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(" - " + ex.Message);
                log.Error(" - " + ex.InnerException);
                f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                if (tmpFile != null && tmpFile.Exists)
                {
                    tmpFile.Delete();
                }
            }
            finally
            {
                log.Info("Move file to " + f.FullName);
                log.Info("End import file");
            }
            return result;
        }

        public static void ImportDistInfo()
        {
            FileInfo[] FileList = dirDownload.GetFiles("SPW2_DistributorInfo*");

            foreach (FileInfo f in FileList)
                ImportDistributorFile(f);
        }

        public static void ImportDistInfo(DirectoryInfo d)
        {
            FileInfo[] FileList = d.GetFiles("SPW2_DistributorInfo*");

            foreach (FileInfo f in FileList)
                ImportDistributorFile(f);
        }
        #endregion

        #region 'Outlet Info'
        /// <summary>
        /// Import a file as outlet info
        /// </summary>
        /// <param name="f">FileInfo of the import file</param>
        /// <returns>'1' when import successful / '0' when import failed</returns>
        public static int ImportOutletFile(FileInfo f)
        {
            int result = 1;
            FileInfo tmpFile = null;
            try
            {
                log.Info("Begin import file " + f.Name);

                Cryptography encode = new Cryptography();
                string pwd = encode.GenPWDByFilename(f.Name);
                Zip.UnzipFile(f.FullName, dirExtract.FullName, pwd);

                log.Info(" - " + f.Name + " decrypted successful");

                FileInfo[] XmlList = dirExtract.GetFiles("SPW2_OutletInfo*");
                foreach (FileInfo xmlFile in XmlList)
                {
                    tmpFile = xmlFile;
                    DataTable dt = new DataTable();
                    dt.ReadXml(xmlFile.FullName);
                    foreach (DataRow dr in dt.Rows)
                    {
                        OutletBO obj = new OutletBO(dr[0].ToString().Trim(),
                            dr[1].ToString().Trim(),
                            dr[2].ToString().Trim(),
                            dr[3].ToString().Trim(),
                            dr[4].ToString().Trim(),
                            dr[5].ToString().Trim(),
                            dr[6].ToString().Trim(),
                            dr[7].ToString().Trim(),
                            dr[8].ToString().Trim());
                        obj.ConvertToTCVN();
                        if (obj.Save() == -1)
                        {
                            result = 0;
                            break;
                        }
                    }
                    xmlFile.Delete();
                    log.Info(" - " + xmlFile.Name + " is imported successful");
                }
                log.Info(" - " + f.Name + " is imported successful");
                if (result == 1)
                {
                    f.MoveTo(Path.Combine(dirBackup.FullName, AddImportTimeSuffix(f.Name)));
                }
                else
                {
                    f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                }
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(" - " + ex.Message);
                log.Error(" - " + ex.InnerException);
                f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                if (tmpFile != null && tmpFile.Exists)
                {
                    tmpFile.Delete();
                }
            }
            finally
            {
                log.Info("Move file to " + f.FullName);
                log.Info("End import file");
            }
            return result;
        }

        public static void ImportOutletInfo()
        {
            FileInfo[] FileList = dirDownload.GetFiles("SPW2_OutletInfo*");
            foreach (FileInfo f in FileList)
                ImportOutletFile(f);
        }

        public static void ImportOutletInfo(DirectoryInfo d)
        {
            FileInfo[] FileList = d.GetFiles("SPW2_OutletInfo*");
            foreach (FileInfo f in FileList)
                ImportOutletFile(f);
        }
        #endregion

        #region 'ActualTarget'

        public static bool IsImported(string ProgramID, string ShipToCode)
        {
            string strSQL = "Select * from fpt_HO_SPW2_ActualTarget_Detail Where ProgramID = @ProgramID and ShipToCode = @ShipToCode";
            List<ParameterObject> lstParams = new List<ParameterObject>();
            lstParams.Add(new ParameterObject("@ProgramID", ProgramID));
            lstParams.Add(new ParameterObject("@ShipToCode", ShipToCode));

            DataTable dt = DataAccessObject.GetDataTableBySQL(strSQL, lstParams);
            if (dt.Rows.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static int ImportActualTargetFile(FileInfo f)
        {
            int result = 1;
            FileInfo tmpFile = null;
            try
            {
                log.Info("Begin import file " + f.Name);

                Cryptography encode = new Cryptography();
                string pwd = encode.GenPWDByFilename(f.Name);
                Zip.UnzipFile(f.FullName, dirExtract.FullName, pwd);

                log.Info(" - " + f.Name + " decrypted successful");

                FileInfo[] XmlList = dirExtract.GetFiles("SPW2*ActualTarget*");
                foreach (FileInfo xmlFile in XmlList)
                {
                    tmpFile = xmlFile;
                    DataTable dt = new DataTable();
                    dt.ReadXml(xmlFile.FullName);

                    if (IsImported(dt.Rows[0][1].ToString().Trim(), dt.Rows[0][0].ToString().Trim()))
                    {
                        log.Info("Actual target of Program '" + dt.Rows[0][1].ToString().Trim() + "' from ShipToCode '" + dt.Rows[0][0].ToString().Trim() + "' is imported before");
                        result = 2;
                    }
                    else
                    {

                        foreach (DataRow dr in dt.Rows)
                        {


                            ActualTargetBO obj = new ActualTargetBO(dr[0].ToString().Trim(),
                                dr[1].ToString().Trim(),
                                dr[2].ToString().Trim(),
                                dr[3].ToString().Trim(),
                                dr[4].ToString().Trim(),
                                dr[5].ToString().Trim(),
                                dr[6].ToString().Trim(),
                                dr[7].ToString().Trim(),
                                Convert.ToInt16(dr[8].ToString().Trim()),
                                Convert.ToInt16(dr[9].ToString().Trim()),
                                Convert.ToDecimal(dr[10].ToString().Trim()),
                                Convert.ToDecimal(dr[11].ToString().Trim()),
                                Convert.ToDecimal(dr[12].ToString().Trim()),
                                Convert.ToDouble(dr[13].ToString().Trim()),
                                Convert.ToDecimal(dr[14].ToString().Trim()),
                                Convert.ToDecimal(dr[15].ToString().Trim()),
                                Convert.ToDecimal(dr[16].ToString().Trim()),
                                DateTime.Parse(dr[17].ToString().Trim()),
                                DateTime.Parse(dr[18].ToString().Trim()),
                                dr[19].ToString().Trim(),
                                0);
                            obj.ConvertToTCVN();
                            obj.Insert();
                            if (obj.Insert() == -1)
                            {
                                result = 0;
                                break;
                            }
                        }
                    }
                    xmlFile.Delete();
                    log.Info(" - " + xmlFile.Name + " is imported successful");
                }
                log.Info(" - " + f.Name + " is imported successful");
                if (result == 1)
                {
                    f.MoveTo(Path.Combine(dirBackup.FullName, AddImportTimeSuffix(f.Name)));
                }
                else
                {
                    f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                }
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(" - " + ex.Message);
                log.Error(" - " + ex.InnerException);
                f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                if(tmpFile!=null && tmpFile.Exists)
                {
                    tmpFile.Delete();
                }
            }
            finally
            {
                log.Info("Move file to " + f.FullName);
                log.Info("End import file");
            }
            return result;
        }

        public static void ImportActualTarget()
        {
            FileInfo[] FileList = dirDownload.GetFiles("SPW2*ActualTarget*");
            foreach (FileInfo f in FileList)
                ImportActualTargetFile(f);
        }

        public static void ImportActualTarget(DirectoryInfo d)
        {
            FileInfo[] FileList = d.GetFiles("SPW2*ActualTarget*");
            foreach (FileInfo f in FileList)
                ImportActualTargetFile(f);
        }
        #endregion

        #region 'TO By Cust'
        public static int ImportTOByCustFile(FileInfo f)
        {
            int result = 1;
            try
            {
                log.Info("Begin import file " + f.Name);

                Cryptography encode = new Cryptography();
                string pwd = encode.GenPWDByFilename(f.Name);
                Zip.UnzipFile(f.FullName, dirExtract.FullName, pwd);

                log.Info(" - " + f.Name + " decrypted successful");

                FileInfo[] XmlList = dirExtract.GetFiles("SPW2*ActualTOByCust*");
                foreach (FileInfo xmlFile in XmlList)
                {
                    DataTable dt = new DataTable();
                    dt.ReadXml(xmlFile.FullName);
                    foreach (DataRow dr in dt.Rows)
                    {
                        TOByCustBO obj = new TOByCustBO(dr[1].ToString(),
                            dr[0].ToString(),
                            dr[2].ToString(),
                            dr[3].ToString(),
                            dr[4].ToString(),
                            dr[5].ToString(),
                            dr[6].ToString(),
                            dr[7].ToString(),
                            Convert.ToInt16(dr[8].ToString()),
                            Convert.ToInt16(dr[9].ToString()),
                            Convert.ToDecimal(dr[10].ToString()),
                            Convert.ToDecimal(dr[11].ToString()),
                            Convert.ToDecimal(dr[12].ToString()),
                            Convert.ToDecimal(dr[13].ToString()),
                            Convert.ToDecimal(dr[14].ToString()),
                            Convert.ToDecimal(dr[15].ToString()),
                            Convert.ToDecimal(dr[16].ToString()),
                            Convert.ToDecimal(dr[17].ToString()),
                            Convert.ToDecimal(dr[18].ToString()),
                            Convert.ToDecimal(dr[19].ToString()),
                            Convert.ToDecimal(dr[20].ToString()),
                            Convert.ToDecimal(dr[21].ToString()),
                            Convert.ToDecimal(dr[22].ToString()),
                            Convert.ToDecimal(dr[23].ToString()),
                            Convert.ToDecimal(dr[24].ToString()),
                            Convert.ToDecimal(dr[25].ToString()),
                            Convert.ToDecimal(dr[26].ToString()),
                            Convert.ToDecimal(dr[27].ToString()),
                            Convert.ToSingle(dr[28].ToString()),
                            Convert.ToDecimal(dr[29].ToString()),
                            DateTime.Parse(dr[30].ToString()));
                        obj.ConvertToTCVN();
                        if (obj.Insert() == -1)
                        {
                            result = 0;
                            break;
                        }
                    }
                    xmlFile.Delete();
                    log.Info(" - " + xmlFile.Name + " is imported successful");
                }
                log.Info(" - " + f.Name + " is imported successful");
                if (result == 1)
                {
                    f.MoveTo(Path.Combine(dirBackup.FullName, AddImportTimeSuffix(f.Name)));
                }
                else
                {
                    f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                }
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(" - " + ex.Message);
                log.Error(" - " + ex.InnerException);
                f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
            }
            finally
            {
                log.Info("Move file to " + f.FullName);
                log.Info("End import file");
            }
            return result;
        }

        public static void ImportTOByCust()
        {
            FileInfo[] FileList = dirDownload.GetFiles("SPW2*ActualTOByCust*");
            foreach (FileInfo f in FileList)
                ImportTOByCustFile(f);
        }

        public static void ImportTOByCust(DirectoryInfo d)
        {
            FileInfo[] FileList = d.GetFiles("SPW2*ActualTOByCust*");
            foreach (FileInfo f in FileList)
                ImportTOByCustFile(f);
        }
        #endregion

        #region 'TO By Cat'
        public static int ImportTOByCatFile(FileInfo f)
        {
            int result = 1;
            try
            {
                log.Info("Begin import file " + f.Name);

                Cryptography encode = new Cryptography();
                string pwd = encode.GenPWDByFilename(f.Name);
                Zip.UnzipFile(f.FullName, dirExtract.FullName, pwd);

                log.Info(" - " + f.Name + " decrypted successful");

                FileInfo[] XmlList = dirExtract.GetFiles("SPW2*ActualTOByCAT*");
                foreach (FileInfo xmlFile in XmlList)
                {
                    DataTable dt = new DataTable();
                    dt.ReadXml(xmlFile.FullName);
                    foreach (DataRow dr in dt.Rows)
                    {
                        TOByCatBO obj = new TOByCatBO(dr[1].ToString(),
                            dr[0].ToString(),
                            dr[2].ToString(),
                            dr[3].ToString(),
                            dr[4].ToString(),
                            dr[5].ToString(),
                            dr[6].ToString(),
                            dr[7].ToString(),
                            dr[8].ToString(),
                            Convert.ToDecimal(dr[9].ToString()),
                            Convert.ToDecimal(dr[10].ToString()),
                            Convert.ToDecimal(dr[11].ToString()),
                            Convert.ToDecimal(dr[12].ToString()),
                            Convert.ToDecimal(dr[13].ToString()),
                            Convert.ToDecimal(dr[14].ToString()),
                            Convert.ToDecimal(dr[15].ToString()),
                            Convert.ToDecimal(dr[16].ToString()),
                            Convert.ToDecimal(dr[17].ToString()),
                            Convert.ToDecimal(dr[18].ToString()),
                            Convert.ToDecimal(dr[19].ToString()),
                            Convert.ToDecimal(dr[20].ToString()),
                            Convert.ToDecimal(dr[21].ToString()),
                            Convert.ToDecimal(dr[22].ToString()),
                            Convert.ToDecimal(dr[23].ToString()),
                            Convert.ToDecimal(dr[24].ToString()),
                            Convert.ToDecimal(dr[25].ToString()),
                            Convert.ToDecimal(dr[26].ToString()),
                            DateTime.Parse(dr[27].ToString()));
                        obj.ConvertToTCVN();
                        if (obj.Insert() == -1)
                        {
                            result = 0;
                            break;
                        }
                    }
                    xmlFile.Delete();
                    log.Info(" - " + xmlFile.Name + " is imported successful");
                }
                log.Info(" - " + f.Name + " is imported successful");
                if (result == 1)
                {
                    f.MoveTo(Path.Combine(dirBackup.FullName, AddImportTimeSuffix(f.Name)));
                }
                else
                {
                    f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                }
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(" - " + ex.Message);
                log.Error(" - " + ex.InnerException);
                f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
            }
            finally
            {
                log.Info("Move file to " + f.FullName);
                log.Info("End import file");
            }
            return result;
        }

        public static void ImportTOByCat()
        {
            FileInfo[] FileList = dirDownload.GetFiles("SPW2*ActualTOByCust*");
            foreach (FileInfo f in FileList)
                ImportTOByCatFile(f);
        }

        public static void ImportTOByCat(DirectoryInfo d)
        {
            FileInfo[] FileList = d.GetFiles("SPW2*ActualTOByCust*");
            foreach (FileInfo f in FileList)
                ImportTOByCatFile(f);
        }
        #endregion

        #region 'Retailer TO Detail'
        public static int ImportRetailerTODetailFile(FileInfo f)
        {
            int result = 1;
            try
            {
                log.Info("Begin import file " + f.Name);

                Cryptography encode = new Cryptography();
                string pwd = encode.GenPWDByFilename(f.Name);
                Zip.UnzipFile(f.FullName, dirExtract.FullName, pwd);

                log.Info(" - " + f.Name + " decrypted successful");

                FileInfo[] XmlList = dirExtract.GetFiles("SPW2*TODetail*");
                foreach (FileInfo xmlFile in XmlList)
                {
                    DataTable dt = new DataTable();
                    dt.ReadXml(xmlFile.FullName);
                    foreach (DataRow dr in dt.Rows)
                    {
                        RetailerTODetail obj = new RetailerTODetail(dr[0].ToString(),
                            dr[1].ToString(),
                            dr[2].ToString(),
                            dr[3].ToString(),
                            dr[4].ToString(),
                            dr[5].ToString(),
                            dr[6].ToString(),
                            dr[7].ToString(),
                            dr[8].ToString(),
                            Convert.ToDecimal(dr[9].ToString()),
                            Convert.ToInt16(dr[10].ToString()),
                            Convert.ToInt16(dr[11].ToString()),
                            DateTime.Parse(dr[12].ToString()),
                            DateTime.Parse(dr[13].ToString()),
                            DateTime.Parse(dr[14].ToString()));
                        obj.ConvertToTCVN();
                        if (obj.Insert() == -1)
                        {
                            result = 0;
                            break;
                        }
                    }
                    xmlFile.Delete();
                    log.Info(" - " + xmlFile.Name + " is imported successful");
                }
                log.Info(" - " + f.Name + " is imported successful");
                if (result == 1)
                {
                    f.MoveTo(Path.Combine(dirBackup.FullName, AddImportTimeSuffix(f.Name)));
                }
                else
                {
                    f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                }
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(" - " + ex.Message);
                log.Error(" - " + ex.InnerException);
                f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
            }
            finally
            {
                log.Info("Move file to " + f.FullName);
                log.Info("End import file");
            }
            return result;
        }

        public static void ImportRetailerTODetail()
        {
            FileInfo[] FileList = dirDownload.GetFiles("SPW2*TODetail*");
            foreach (FileInfo f in FileList)
                ImportTOByCatFile(f);
        }

        public static void ImportRetailerTODetail(DirectoryInfo d)
        {
            FileInfo[] FileList = d.GetFiles("SPW2*TODetail*");
            foreach (FileInfo f in FileList)
                ImportTOByCatFile(f);
        }
        #endregion

        #region 'TO Detail'
        public static int ImportTODetailFile(FileInfo f)
        {
            int result = 1;
            try
            {
                log.Info("Begin import file " + f.Name);

                Cryptography encode = new Cryptography();
                string pwd = encode.GenPWDByFilename(f.Name);
                Zip.UnzipFile(f.FullName, dirExtract.FullName, pwd);

                log.Info(" - " + f.Name + " decrypted successful");

                FileInfo[] XmlList = dirExtract.GetFiles("SPW2*TODetail*");
                foreach (FileInfo xmlFile in XmlList)
                {
                    DataTable dt = new DataTable();
                    dt.ReadXml(xmlFile.FullName);
                    foreach (DataRow dr in dt.Rows)
                    {
                        TODetail obj = new TODetail(dr[0].ToString(),
                            dr[1].ToString(),
                            dr[2].ToString(),
                            dr[3].ToString(),
                            dr[4].ToString(),
                            dr[5].ToString(),
                            dr[6].ToString(),
                            dr[7].ToString(),
                            dr[8].ToString(),
                            dr[9].ToString(),
                            Convert.ToDecimal(dr[10].ToString()),
                            DateTime.Parse(dr[11].ToString()));
                        obj.ConvertToTCVN();
                        if (obj.Insert() == -1)
                        {
                            result = 0;
                            break;
                        }
                    }
                    xmlFile.Delete();
                    log.Info(" - " + xmlFile.Name + " is imported successful");
                }
                log.Info(" - " + f.Name + " is imported successful");
                if (result == 1)
                {
                    f.MoveTo(Path.Combine(dirBackup.FullName, AddImportTimeSuffix(f.Name)));
                }
                else
                {
                    f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
                }
            }
            catch (Exception ex)
            {
                result = 0;
                log.Error(" - " + ex.Message);
                log.Error(" - " + ex.InnerException);
                f.MoveTo(Path.Combine(dirBackupError.FullName, AddImportTimeSuffix(f.Name)));
            }
            finally
            {
                log.Info("Move file to " + f.FullName);
                log.Info("End import file");
            }
            return result;
        }

        public static void ImportTODetail()
        {
            FileInfo[] FileList = dirDownload.GetFiles("SPW2*TODetail*");
            foreach (FileInfo f in FileList)
                ImportTOByCatFile(f);
        }

        public static void ImportTODetail(DirectoryInfo d)
        {
            FileInfo[] FileList = d.GetFiles("SPW2*TODetail*");
            foreach (FileInfo f in FileList)
                ImportTOByCatFile(f);
        }
        #endregion
    }
}
